#include "minimusic.h"
#include "ui_minimusic.h"
#include "btfrom.h"

#include <QMouseEvent>
#include <QGraphicsDropShadowEffect>
#include <QDebug>
#include <QVector>
#include <QString>
#include <QJsonObject>
#include <QJsonArray>
#include <QFileDialog>
#include <QImage>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSystemTrayIcon>
#include <QMenu>

MiniMusic::MiniMusic(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MiniMusic)
{
    ui->setupUi(this);

    srand(time(nullptr));

    this->initUI();

    this->initSqliter();

    this->initMusicList();

    this->initPlayer();
}

MiniMusic::~MiniMusic()
{
    delete ui;
}

void MiniMusic::PageChange(int id)
{
    ui->stackedWidget->setCurrentIndex(id);

    //清除之前btFrom的颜色背景
    QList<BTFrom*> btFromList = this->findChildren<BTFrom*>();

    for (auto btFrom : btFromList)
    {
        if (btFrom->GetId() != id)
        {
            btFrom->clearBackground();
        }
    }

    this->isDrag = false;
}

void MiniMusic::initUI()
{
    this->setWindowFlag(Qt::FramelessWindowHint);
    // 设置窗⼝背景透明
     this->setAttribute(Qt::WA_TranslucentBackground);

    this->setWindowIcon(QIcon(":/image/tubiao.png"));

    ui->max->setEnabled(false);

    //设置系统托盘
    QSystemTrayIcon* trayIcon = new QSystemTrayIcon(QIcon(":/image/tubiao.png"),this);
    trayIcon->show();

    //给托盘添加菜单
    QMenu* trayMenu = new QMenu();
    trayMenu->addAction("显示",this,&MiniMusic::showNormal);
    trayMenu->addAction("退出",this,&MiniMusic::MinMusicQuit);

    trayIcon->setContextMenu(trayMenu);

    //QAction* action = new QAction("显示");


    //给窗口设置阴影效果
    QGraphicsDropShadowEffect* shadow = new QGraphicsDropShadowEffect(this);
    // 设置阴影参数
    shadow->setBlurRadius(10);                  // 阴影模糊半径
    shadow->setOffset(0, 0);                    // 阴影偏移 (x, y)
    shadow->setColor(QColor(0, 0, 0, 160));     // 阴影颜色（带透明度）

    this->setGraphicsEffect(shadow);

    //设置默认本地下载窗口
    ui->stackedWidget->setCurrentIndex(4);
    //设置本地下载动画显示
    ui->local->showAnaimal(true);
    
    //设置默认当前页面
    currentPage = ui->localPage;

    //设置BtFrom
    ui->Rec->seticon(":/image/rec.png","推荐",0);
    ui->audio->seticon(":/image/radio.png","电台",1);
    ui->music->seticon(":/image/music.png","音乐馆",2);
    ui->like->seticon(":/image/like.png","我喜欢",3);
    ui->local->seticon(":/image/local.png","本地下载",4);
    ui->recent->seticon(":/image/recent.png","最近播放",5);

    connect(ui->Rec,&BTFrom::BtClick,this,&MiniMusic::PageChange);
    connect(ui->audio,&BTFrom::BtClick,this,&MiniMusic::PageChange);
    connect(ui->music,&BTFrom::BtClick,this,&MiniMusic::PageChange);
    connect(ui->like,&BTFrom::BtClick,this,&MiniMusic::PageChange);
    connect(ui->local,&BTFrom::BtClick,this,&MiniMusic::PageChange);
    connect(ui->recent,&BTFrom::BtClick,this,&MiniMusic::PageChange);

    connect(ui->localPage,&CommonPage::updateLikeMusic,this,&MiniMusic::on_update_page);
    connect(ui->lickePage,&CommonPage::updateLikeMusic,this,&MiniMusic::on_update_page);
    connect(ui->recentPage,&CommonPage::updateLikeMusic,this,&MiniMusic::on_update_page);

    //randomPiction();

    ui->recMusicBox->initRecBoxUi(randomPiction(),1);
    ui->supplyMusicBox->initRecBoxUi(randomPiction(),2);

    ui->lickePage->setMuisListType(PageType::LIKE_Page);
    ui->lickePage->setCommonPageUi("我喜欢",":/image/ilikebg.png");
    ui->localPage->setMuisListType(PageType::LOCAL_Page);
    ui->localPage->setCommonPageUi("本地音乐",":/image/localbg.png");
    ui->recentPage->setMuisListType(PageType::HISTOARY_Page);
    //ui->recPage

    ui->recentPage->setCommonPageUi("最近播放",":/image/recentbg.png");

    this->volume = new VolumeTool(this);

    //实例化LrcWod对象
    this->lrcPage = new LrcPage(this);
    this->lrcPage->move(10,10);

    this->lrcPage->hide();

    //初始化上移动画
    lrcPageAnimal = new QPropertyAnimation(lrcPage,"geometry",this);
    lrcPageAnimal->setDuration(250);
    lrcPageAnimal->setStartValue(QRect(10,10 + lrcPage->height(),lrcPage->width(),lrcPage->height()));
    lrcPageAnimal->setEndValue(QRect(10,10,lrcPage->width(),lrcPage->height()));

    //歌词的按钮关联信号和槽函数
    connect(ui->lrcWord,&QPushButton::clicked,this,&MiniMusic::onLrcWordCilcked);

    //处理静音
    connect(volume,&VolumeTool::setMusicMuted,this,&MiniMusic::setPlayerMuted);
    //处理音量大小
    connect(volume,&VolumeTool::setMusicVolume,this,&MiniMusic::setPlayerVolume);

    //播放控制区域图标设置
    ui->play->setIcon(QIcon(":/image/play_2.png"));
    ui->playMode->setIcon(QIcon(":/image/list_play.png"));


    //MusicSlider位置改变
    connect(ui->processBar,&MusicSlider::setMusicSilderPostion,this,&MiniMusic::onMusicSliderChanged);


}

void MiniMusic::initSqliter()
{
    //1. 数据库驱动加载
    sqlite = QSqlDatabase::addDatabase("QSQLITE");
    //2. 设置数据库名称
    sqlite.setDatabaseName("MinMusic.db");
    //3. 打开
    if (!sqlite.open())
    {
        QMessageBox::critical(this,"MinMusic","数据库打开失败!!!");
        return;
    }

    qDebug() << "MInmusic数据库连接成功";

    //4. 创建表

    QString sql = "create table if not exists MusicInfo(\
                        id integer primary key autoincrement,\
                        musicId varchar(50) unique,\
                        musicSinger varchar(50),\
                        musicName varchar(200),\
                        musicAlbumn varchar(50),\
                        musicUrl varchar(256),\
                        duration bigint,\
                        isLike integer,\
                        isHistory integer)";
    QSqlQuery query;
    if (!query.exec(sql))
    {
        QMessageBox::critical(this,"MInMusic","初始化错误!!!");
        return;
    }

    qDebug() << "MinMuic表创建成功!!!";

}

void MiniMusic::initMusicList()
{
    musicList.readToDB();


    ui->lickePage->reFresh(musicList);
    ui->localPage->reFresh(musicList);
    ui->recentPage->reFresh(musicList);

}

void MiniMusic::initPlayer()
{
    //1. 初始化媒体播放类
    player = new QMediaPlayer(this);
    playList = new QMediaPlaylist(this);

    connect(ui->play,&QPushButton::clicked,this,&MiniMusic::onPlayMusic);

    //2. 设置播放模式
    playList->setPlaybackMode(QMediaPlaylist::Loop);

    //3. 将播放列表设置到播放媒体对象中
    player->setPlaylist(playList);

    //4. 设置默认音量大小
    player->setVolume(20);

    //关联QMediaPlayer信号
    connect(player,&QMediaPlayer::stateChanged,this,&MiniMusic::onPlayerStateChanged);

    //关联QMediaPlayer::durationChanged信号
    connect(player,&QMediaPlayer::durationChanged,this,&MiniMusic::onDurationChanged);

    connect(player,&QMediaPlayer::positionChanged,this,&MiniMusic::onPositionChanged);

    connect(ui->playUp,&QPushButton::clicked,this,&MiniMusic::onPlayUpClicked);
    connect(ui->playDown,&QPushButton::clicked,this,&MiniMusic::onPlayDownClicked);

    connect(ui->playMode,&QPushButton::clicked,this,&MiniMusic::onPlaybackModeClicked);

    connect(playList,&QMediaPlaylist::playbackModeChanged,this,&MiniMusic::onPlaybackModeChnaged);

    connect(ui->lickePage,&CommonPage::playAll,this,&MiniMusic::onPlayAll);
    connect(ui->localPage,&CommonPage::playAll,this,&MiniMusic::onPlayAll);
    connect(ui->recentPage,&CommonPage::playAll,this,&MiniMusic::onPlayAll);

    //处理likepgae,localpage,recentpage中的ListBoxItem双击
    connect(ui->lickePage,&CommonPage::playMusicByIndex,this,&MiniMusic::palyMusicByIndex);
    connect(ui->localPage,&CommonPage::playMusicByIndex,this,&MiniMusic::palyMusicByIndex);
    connect(ui->recentPage,&CommonPage::playMusicByIndex,this,&MiniMusic::palyMusicByIndex);

    // 当playlist中播放源发生变化时
    connect(playList,&QMediaPlaylist::currentIndexChanged,this,&MiniMusic::onCurrentIndexChanged);

    connect(player,&QMediaPlayer::metaDataAvailableChanged,this,&MiniMusic::onMetaDataAvailableChanged);

}



QJsonArray MiniMusic::randomPiction()
{
    QVector<QString> vectImageName;

    vectImageName << "001.png" <<"003.png" << "004.png" << "005.png"
                  << "006.png" << "007.png" <<"008.png" << "009.png" << "010.png"
                  << "011.png" << "012.png" <<"013.png" << "014.png" << "015.png"
                  << "016.png" << "017.png" <<"018.png" << "019.png" << "020.png"
                  << "021.png" << "022.png" <<"023.png" << "024.png" << "025.png"
                  << "026.png" << "027.png" <<"028.png" << "029.png" << "030.png"
                  << "031.png" << "032.png" <<"033.png" << "034.png" << "035.png"
                  << "036.png" << "037.png" <<"038.png" << "039.png" << "040.png";

    std::random_shuffle(vectImageName.begin(),vectImageName.end());

    QJsonArray objArray;

    for (int i = 0; i < vectImageName.size(); i++)
    {
        QJsonObject obj;
        obj.insert("path",":/image/rec/" + vectImageName[i]);
        QString strText = QString("推荐-%1").arg(i,3,10,QChar('0'));
        obj.insert("text",strText);

        objArray.append(obj);
    }

    return objArray;
}

void MiniMusic::updateBtformAnimal()
{
    // 通过currentPage获取其在stackwWidget中的索引
    int index = ui->stackedWidget->indexOf(currentPage);

    if (-1 == index)
    {
        qDebug() << "该页面不存在";
        return;
    }

    //获取MinMusic界面上的btForm
    QList<BTFrom*> btForms = this->findChildren<BTFrom*>();

    for (auto btForm : btForms)
    {
        if (btForm->GetId() == index)
        {
            //将currentPage对应的btForm找到了
            btForm->showAnaimal(true);
        }
        else
        {
            btForm->showAnaimal(false);
        }
    }


}

void MiniMusic::MinMusicQuit()
{
    //写入数据库
    this->musicList.writeToDB();

    //断开与SQLite的链接
    sqlite.close();

    //关闭窗口
    this->close();
}

void MiniMusic::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        this->isDrag = true;

        dragPosition = event->globalPos() - this->frameGeometry().topLeft();
        return;
    }

    this->QWidget::mousePressEvent(event);
}

void MiniMusic::mouseMoveEvent(QMouseEvent *event)
{  
   if (event->buttons() == Qt::LeftButton  && isDrag)
   {
        this->move(event->globalPos() - dragPosition);
        return;
   }

   this->QWidget::mouseMoveEvent(event);
}

void MiniMusic::onMetaDataAvailableChanged(bool available)
{
    (void) available;
    // 歌曲名称, 歌曲作者直接到Music对象中获取
    QString musicId = currentPage->getMusicByIndex(currentIndex);

    auto it = musicList.findMusicByMusicId(musicId);

    QString musicName;
    QString musicSinger;
    QUrl musicUrl;

    if (it != musicList.end())
    {
        musicName = it->getMusicName();
        musicSinger = it->getMusicSinger();
        musicUrl = it->getMusicUrl();
    }

    ui->musicName->setText(musicName);
    ui->musicSinger->setText(musicSinger);

    //获取封面图,通过源数据来获取
   // player->setMedia(musicUrl);

//    while(!player->isMetaDataAvailable())
//    {
//        QCoreApplication::processEvents();
//    }

    QVariant image = player->metaData("ThumbnailImage");

    if (image.isValid())
    {
        QImage coverimage = image.value<QImage>();
        ui->musiCover->setPixmap(QPixmap::fromImage(coverimage));
        ui->musiCover->setScaledContents(true);
        currentPage->setMusicImage(QPixmap::fromImage(coverimage));
    }
    else
    {
        qDebug() << "歌曲没有封面图";
        //可以设置默认图片
        QString path = ":/image/rec/005.png";
        ui->musiCover->setPixmap(path);
        ui->musiCover->setScaledContents(true);
        currentPage->setMusicImage(path);
    }

    //解析歌曲的 LRC歌词
    if (it != musicList.end())
    {
        QString lrcPath = it->getMusicFilePath();

        //解析lrc文件
        lrcPage->praseLrcFile(lrcPath);
    }

}

void MiniMusic::onMusicSliderChanged(float ration)
{
    //根据进度条与总宽度的比率,更新当前播放时间
    qint64 duration = this->totaltime * ration;
    ui->currentTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));

    //时间修改了之后,播放时间也需要修改
    player->setPosition(duration);
}




void MiniMusic::on_min_clicked()
{
    this->showMinimized();
}


void MiniMusic::on_quit_clicked()
{
    this->hide();
}

void MiniMusic::on_addLocal_clicked()
{
    //QFileDialog* fileDialog = new QFileDialog(this);
    QFileDialog fileDialog(this);
    fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
    //设置窗口标题
    fileDialog.setWindowTitle("添加本地下载音乐");
    //文件对话框默认的打开路径
    QDir dir = QDir::currentPath();
    dir.cdUp();
    QString path = dir.path();
    path = path + "/MiniMusic";
    fileDialog.setDirectory(path);
    //设置一次打开多个
    fileDialog.setFileMode(QFileDialog::ExistingFiles);
    //设置文件过滤
    //fileDialog.setNameFilter("代码文件(*.h *.c *.cpp)");

//    QStringList filters;
//    filters << "Image files (*.png *.xpm *.jpg)"
//            << "Text files (*.txt)"
//            << "Any files (*)";

//    fileDialog.setNameFilters(filters);
    //通过MIME类型过滤
    QStringList mimeTypeFilters;
     mimeTypeFilters << "image/jpeg"
                 << "image/png"
                 << "application/octet-stream";


     fileDialog.setMimeTypeFilters(mimeTypeFilters);


     if(QDialog::Accepted == fileDialog.exec())
     {


        QList<QUrl> fileUrls = fileDialog.selectedUrls();

        //fileUrls: 内部存放的是刚刚选中的文件路径的URL
        //将文件下载信息填充到本地下载

        //将所有的音乐文件添加到音乐列表中,MusicList
        musicList.addMusicsByUrl(fileUrls);

        //将歌曲信息更新到CommonPage页面的listWidget中
         ui->stackedWidget->setCurrentIndex(4);

         ui->localPage->reFresh(musicList);

         //将localPage中的歌曲添加到媒体播放列表中
         ui->localPage->addMusicToPlayerList(musicList,playList);

     }


}

void MiniMusic::on_volume_clicked()
{
    //1. 获取ui->volume控件的全局坐标，
    QPoint point = ui->volume->mapToGlobal(QPoint(0,0));
    //2. 计算相对于需要移动位置的坐标
    int x = point.x() + ui->volume->width()/2 - this->volume->width()/2;
    int y = point.y() - this->volume->height();
    //3. 移动
    this->volume->move(x,y);
    //4. 显示
    this->volume->show();

    //ui->volume->frameGeometry().topLeft();

    //QPoint VolumeLeftTop = point - QPoint()

}

void MiniMusic::on_update_page(bool isLike, const QString &musicId)
{
    //1. 修改状态
    auto it = musicList.findMusicByMusicId(musicId);

    if (it != musicList.end())
    {
        it->setIsLike(isLike);
    }

    //2. 更新Page页面的歌曲列表
    ui->lickePage->reFresh(musicList);
    ui->localPage->reFresh(musicList);
    ui->recentPage->reFresh(musicList);


}

void MiniMusic::onLrcWordCilcked()
{
    lrcPage->show();

    lrcPageAnimal->start();
}

///////////////////////////////////////////////////////////
//播放控制说明


//播放和暂停
void MiniMusic::onPlayMusic()
{
    if (player->state() == QMediaPlayer::PlayingState)
    {
        //播放点击按钮,应该暂停
        player->pause();
        //ui->play->setIcon(QIcon(":/image/play3.png"));
    }
    else if (player->state() == QMediaPlayer::PausedState)
    {
        //暂停状态中点击,应该继续播放
        player->play();
        //ui->play->setIcon(QIcon(":/image/play_on.png"));
    }
    else if (player->state() == QMediaPlayer::StoppedState)
    {
        //刚开始默认为停止状态,当点击播放按钮时,直接播放即可
        player->play();
        //ui->play->setIcon(QIcon(":/image/play3.png"));
    }
    else
    {
        qDebug() << player->errorString();
    }
}

void MiniMusic::onPlayerStateChanged()
{
    if (player->state() == QMediaPlayer::PlayingState)
    {
        ui->play->setIcon(QIcon(":/image/play_on.png"));
    }
    else
    {
        ui->play->setIcon(QIcon(":/image/play3.png"));
    }
}

void MiniMusic::onPlayUpClicked()
{
    this->playList->previous();
}

void MiniMusic::onPlayDownClicked()
{
    this->playList->next();
}

void MiniMusic::onPlaybackModeClicked()
{
    //1. 根据当前的模式切换到下一种模式
    //2. 设置Tooltip提示
    //列表循环-->随机播放-->单曲循环
    //当状态发生改变的时候,还需要修改按钮上的图标
    if (playList->playbackMode() == QMediaPlaylist::Loop)
    {
        //随机播放
        playList->setPlaybackMode(QMediaPlaylist::Random);
        ui->playMode->setToolTip("随机播放");
    }
    else if (playList->playbackMode() == QMediaPlaylist::Random)
    {
        //单曲循环
        playList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
        ui->playMode->setToolTip("单曲循环");
    }
    else if (playList->playbackMode() == QMediaPlaylist::CurrentItemInLoop)
    {
        //列表循环
        playList->setPlaybackMode(QMediaPlaylist::Loop);
        ui->playMode->setToolTip("列表循环");
    }
    else
    {
        qDebug() << playList->errorString();
    }

}

void MiniMusic::onPlaybackModeChnaged(QMediaPlaylist::PlaybackMode playBackMode)
{
    if (playBackMode == QMediaPlaylist::Loop)
    {
        ui->playMode->setIcon(QIcon(":/image/list_play.png"));
    }
    else if (playBackMode == QMediaPlaylist::Random)
    {
        ui->playMode->setIcon(QIcon(":/image/shuffle_2.png"));
    }
    else if (playBackMode == QMediaPlaylist::CurrentItemInLoop)
    {
         ui->playMode->setIcon(QIcon(":/image/single_play.png"));
    }
    else
    {
        qDebug() << "暂不支持";
    }

}

void MiniMusic::onPlayAll(PageType page)
{
    // 播放page对应的CommonPage页面的所有歌曲,默认从第0首开始播放
    CommonPage* pagePlay = ui->localPage;

    switch (page)
    {
        case PageType::LIKE_Page:
            pagePlay = ui->lickePage;
        break;
    case PageType::LOCAL_Page:
        pagePlay = ui->localPage;
        break;
    case PageType::HISTOARY_Page:
        pagePlay = ui->recentPage;
        break;
    default:
        qDebug() << "暂不支持的页面";
    }

    playAllMusicOfCommpagePage(pagePlay,0);
}

void MiniMusic::playAllMusicOfCommpagePage(CommonPage *page, int index)
{
    currentPage = page;
    updateBtformAnimal();
    //清空之前playlist页面的歌曲
    playList->clear();

    //添加当前要播放的page页面的所有歌曲
    page->addMusicToPlayerList(musicList,playList);

    //播放默认从第0首
    playList->setCurrentIndex(index);

    player->play();


}

void MiniMusic::palyMusicByIndex(CommonPage *page, int index)
{
    playAllMusicOfCommpagePage(page,index);
}

void MiniMusic::onCurrentIndexChanged(int index)
{
    currentIndex = index;
    //由于Commpage页面中的歌曲和正在播放列表中的歌曲的先后次序是相同的
    QString  musicId = currentPage->getMusicByIndex(index);

    auto it = musicList.findMusicByMusicId(musicId);
    if (it != musicList.end())
    {
        it->setIsHistory(true);
    }

    ui->recentPage->reFresh(musicList);
}

void MiniMusic::setPlayerMuted(bool isMuted)
{
    player->setMuted(isMuted);
}

void MiniMusic::setPlayerVolume(int volume)
{
    player->setVolume(volume);
}

void MiniMusic::onDurationChanged(qint64 duration)
{
    this->totaltime = duration;
    // duration为歌曲的总时长
    //duration / 1000 / 60
    //duration / 1000 % 60

    ui->totalTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));
}

void MiniMusic::onPositionChanged(qint64 position)
{
    //更新当前时间
    ui->currentTime->setText(QString("%1:%2").arg(position/1000/60,2,10,QChar('0')).arg(position/1000%60,2,10,QChar('0')));
    //更新进度条的位置
    ui->processBar->setStep(position / (float)totaltime);

    //在歌词界面同步显示歌词
    if (currentIndex >= 0)
    {
        lrcPage->showLrcWordLine(position);
    }
}

void MiniMusic::on_skin_clicked()
{
    //换肤
    //类似于更换背景颜色或者背景图片
    QMessageBox::information(this,"温馨提示","换肤功能正在开发中...");
}

void MiniMusic::on_max_clicked()
{
    this->showMaximized();
}
